<template>
  <!-- 输入图片验证码的表单项组件 -->
  <el-form-item prop="imageCode">
    <div class="image-code-panel">
      <el-input
        clearable
        size="large"
        placeholder="请输入验证码"
        v-model.trim="props.formData.imageCode"
      >
        <template #prefix>
          <span class="iconfont icon-checkcode"></span>
        </template>
      </el-input>
      <!-- 验证码图片 -->
      <img
        :src="imageCodeUrl"
        class="image-code"
        @click="changeImageCode(props.imageCodeType)"
      />
    </div>
  </el-form-item>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const props = defineProps({
  // 该表单项对应的表单对象
  formData: {
    type: Object,
  },
  // 获取的图片验证码类型（类型不同后端session的key不同，分为登录注册时的验证码（0）、获取邮箱验证码时的验证码（1））
  imageCodeType: {
    type: Number,
    default: 0,
  },
});

/* 获取图片验证码 */
const imageCodeUrl = ref("");
const changeImageCode = async (type = props.imageCodeType) => {
  imageCodeUrl.value =
    proxy.Api.imageCode + "?type=" + type + "&t=" + new Date().getTime();
  // 清空输入框
  props.formData.imageCode = "";
};
changeImageCode(props.imageCodeType);

const formDataRef = ref();

// 让外部可以手动调用更新图片验证码
defineExpose({
  changeImageCode,
});
</script>

<style lang="scss" scoped>
.image-code-panel {
  width: 100%;
  display: flex;
  .image-code {
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>
